package com.xinongbest.sqlSession;

import com.xinongbest.pojo.Configuration;

import java.lang.reflect.*;
import java.util.List;

public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        Executor executor = new SimpleExecutor();
        List<Object> query = executor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return (List<E>) query;
    }

    @Override
    public <E> E selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (E) objects.get(0);
        } else {
            throw new RuntimeException("查询结果为空或者返回结果不唯一");
        }
    }

    @Override
    public <E> E getMapper(Class<?> mapperClass) {
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();
                Type returnType = method.getGenericReturnType();
                String statementId = className + "." + methodName;
                if (returnType instanceof ParameterizedType) {
                    return selectList(statementId, args);
                } else {
                    return selectOne(statementId, args);
                }
            }
        });
        return (E) proxyInstance;
    }
}
